using System;
using System.Diagnostics.Contracts;

namespace OpenWaves.Caching
{
    public class ConcurrentCache<T> : IConcurrentCache<T> where T : class
    {
        private readonly ICache<T> cache;
        private readonly ILockManager lockManager;

        public ConcurrentCache(ICache<T> cache, ILockManager lockManager = null)
        {
            Contract.Requires<ArgumentNullException>(cache != null);

            this.cache = cache;
            this.lockManager = lockManager ?? new MonitorBasedLockManager();
        }

        public T GetOrCreate(string key, Func<CacheEntry<T>> create)
        {
            var value = this.cache.GetValue(key);
            if (value == null)
            {
                this.lockManager.AcquireLock(key);
                try
                {
                    value = this.cache.GetValue(key);
                    if (value == null)
                    {
                        var newEntry = create();
                        this.InsertValue(key, newEntry.Value, newEntry.AbsoluteExpiration);
                        return newEntry.Value;
                    }
                }
                finally
                {
                    this.lockManager.ReleaseLock(key);
                }
            }

            return value;
        }

        public void InsertValue(string key, T value, DateTime absoluteExpiration)
        {
            this.cache.InsertValue(key, value, absoluteExpiration);
        }

        public T GetValue(string key)
        {
            return this.cache.GetValue(key);
        }

        public void EvictValue(string key)
        {
            this.cache.EvictValue(key);
        }
    }
}